//
//  BindSNVC.swift
//  kxf
//
//  Created by Mac on 2024/3/19.
//

import Foundation
import UIKit
import MCToast

class BindSNVC: WHBaseViewVC {
    
    var bindType = ""
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        initUI()
        
    }
    
    lazy var titleVm: RegisterViewHeadTitleVM = {
        let vm = RegisterViewHeadTitleVM.init(frame: CGRect.init(x: 0, y: getNavigationBarHeight()+kFitWidth(10), width: SCREEN_WIDHT, height: kFitWidth(44)))
        vm.titleLabel.text = "信息"
        
        return vm
    }()
    lazy var whiteView : UIView = {
        let vi = UIView()
        vi.backgroundColor = .white
        vi.isUserInteractionEnabled = true
        
        return vi
    }()
    lazy var leftTitleLab : UILabel = {
        let lab = UILabel()
        lab.text = "SN"
        lab.textColor = .black
        lab.font = .systemFont(ofSize: 14, weight: .medium)
        
        return lab
    }()
    lazy var textField : UITextField = {
        let text = UITextField()
        text.placeholder = "请点击右侧扫码绑定码牌"
//        text.isEnabled = false
        if self.bindType == "VOICE_BOX"{
            text.placeholder = "请点击右侧扫码绑定音响"
        }
        text.font = .systemFont(ofSize: 14, weight: .regular)
        
        return text
    }()
    lazy var scanImgView : UIImageView = {
        let img = UIImageView()
        img.setImgLocal(imgName: "scan_icon")
        img.isUserInteractionEnabled = true
        
        let tap = UITapGestureRecognizer.init(target: self, action: #selector(scanAction))
        img.addGestureRecognizer(tap)
        
        return img
    }()
    lazy var bindBtn : UIButton = {
        let btn = UIButton()
        btn.frame = CGRect.init(x: kFitWidth(31), y: SCREEN_HEIGHT - kFitWidth(100) - getBottomSafeAreaHeight(), width: kFitWidth(316), height: kFitWidth(48))
        btn.setTitle("确认", for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.setBackgroundImage(UIImage.init(named: "button_theme_bg"), for: .normal)
        btn.layer.cornerRadius = kFitWidth(24)
        btn.clipsToBounds = true
        btn.titleLabel?.font = .systemFont(ofSize: 16, weight: .regular)
        btn.backgroundColor = .clear
        
        btn.addTarget(self, action: #selector(bindAction), for: .touchUpInside)
        
        return btn
    }()
}

extension BindSNVC{
    @objc func scanAction() {
        let vc = QRCodeScanVC()
        self.navigationController?.pushViewController(vc, animated: true)
        vc.scanResultBlock = {(sn)in
            DLLog(message: "\(sn)")
            let resultArr = sn.components(separatedBy: "sn=")
            if resultArr.count > 1 {
                let snString = resultArr[1]
                self.textField.text = "\(snString)"
            }
        }
    }
    @objc func bindAction() {
//        if self.bindType == "voice"{
//            
//        }else{
//            if textField.text?.count ?? 0 < 3{
//                presentAlertVcNoAction(title: "请扫码获取码牌sn序列号", viewController: self)
//            }else{
//                self.sendQuerySnRequest()
//            }
//        }
        if textField.text?.count ?? 0 < 2{
            presentAlertVcNoAction(title: "请扫码获取sn序列号", viewController: self)
        }else{
            self.sendBindVoiceRequest()
        }
    }
}

extension BindSNVC{
    func initUI() {
        if self.bindType == "VOICE_BOX"{
            initNavi(titleStr: "新增音响")
        }else{
            initNavi(titleStr: "新增码牌")
        }
        
        view.backgroundColor = WHColor_16(colorStr: "F8F8F8")
        
        view.addSubview(titleVm)
        view.addSubview(whiteView)
        whiteView.addSubview(leftTitleLab)
        whiteView.addSubview(textField)
        whiteView.addSubview(scanImgView)
        
        view.addSubview(bindBtn)
        
        setConstrait()
    }
    func setConstrait() {
        whiteView.snp.makeConstraints { make in
            make.left.width.equalToSuperview()
            make.top.equalTo(titleVm.snp.bottom).offset(kFitWidth(1))
            make.height.equalTo(kFitWidth(50))
        }
        leftTitleLab.snp.makeConstraints { make in
            make.left.equalTo(kFitWidth(24))
            make.top.height.equalToSuperview()
        }
        textField.snp.makeConstraints { make in
            make.left.equalTo(kFitWidth(120))
            make.top.height.equalToSuperview()
            make.width.equalTo(kFitWidth(160))
        }
        scanImgView.snp.makeConstraints { make in
            make.right.equalTo(kFitWidth(-20))
            make.centerY.lessThanOrEqualToSuperview()
            make.width.height.equalTo(kFitWidth(28))
        }
//        bindBtn.snp.makeConstraints { make in
//            make.centerX.lessThanOrEqualToSuperview()
//            make.top.equalTo(whiteView.snp.bottom).offset(kFitWidth(40))
//            make.width.equalTo(kFitWidth(316))
//            make.height.equalTo(kFitWidth(48))
//        }
    }
}


extension BindSNVC{
    func sendQuerySnRequest() {
        MCToast.mc_loading()
        WHNetworkUtil.shareManager().GET(urlString: "\(URL_sn_query_status)?sn=\(textField.text ?? "")") { responseObject in
            if responseObject["code"]as? Int ?? -1 == 200{
                self.sendBindRequest()
            }else{
                self.presentAlertVcNoAction(title: "\(responseObject["message"]as? String ?? "")", viewController: self)
            }
        }
    }
    func sendBindRequest() {
        let param:[String:Any] = ["sn":"\(textField.text ?? "")"]
        WHNetworkUtil.shareManager().POST(urlString: URL_sn_bind, parameters: param as [String:AnyObject],isNeedToast: true,vc: self) { responseObject in
            self.presentAlertVc(confirmBtn: "确定", message: "", title: "绑码成功", cancelBtn: nil, handler: { action in
                self.backTapAction()
            }, viewController: self)
        }
    }
    func sendBindVoiceRequest() {
        MCToast.mc_loading()
        let param:[String:Any] = ["sn":"\(textField.text ?? "")",
                                  "type":"\(self.bindType)"]
        WHNetworkUtil.shareManager().POST(urlString: URL_Device_bind, parameters: param as [String:AnyObject],isNeedToast: true,vc: self) { responseObject in
            self.presentAlertVc(confirmBtn: "确定", message: "", title: "新增成功", cancelBtn: nil, handler: { action in
                self.backTapAction()
            }, viewController: self)
        }
    }
}
